package com.cgx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgx.dto.SetmealDto;
import com.cgx.mapper.SetmealMapper;
import com.cgx.pojo.Setmeal;
import com.cgx.pojo.SetmealDish;
import com.cgx.service.SetmealDishService;
import com.cgx.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息——>setmeal
        this.save(setmealDto);

        List<SetmealDish> list = setmealDto.getSetmealDishes();
        list.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐与菜品的关联关系
        setmealDishService.saveBatch(list);
    }

    /**
     * 删除套餐，同时删除套餐和菜品的关系
     * @param ids
     */
    @Override
    public void removeWithDish(List<Long> ids) {
        //删除前先要查询一下套餐状态，保证只有停售的套菜才能删除--这里要抛异常所以在此省略,等以后可以使用前端功能完善
        //删除套餐表——>setmeal
        this.removeByIds(ids);
        //删除关系表——>setmeal_dish
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper);
    }
}
